<!DOCTYPE html>
<html>
	<head>
		<title>复杂事件代理实现机制</title>
		<meta charset="utf-8">
		<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
		<style type="text/css">
			#box {
				background: blue;
			}
		</style>
	</head>
	<body>
		<button id="btn">创建一个dom</button>
		<div id="box">
			<div class="classA">
				<div class="classB">
					<ul>
						<li>lilili</li>
						<li>lilili</li>
						<li><span>我是深层的span</span></li>
					</ul>
				</div>
				<span>kodo</span>
			</div>
		</div>
		<div class="stop">
			<a href="www.baidu.com">www.baidu.com</a>
		</div>
		<div class="parent">
	        <div class="child">我是孩纸</div>
	    </div>
		<script type="text/javascript">
		/*$("#btn").click(function() {
			$(".btn-wrap").append('<button class="btn-test">.btn-test</button>');
		});*/
			/**
			 * @param {Object} agent 委托的dom对象
			 * @param {String} type  事件类型
			 * @param {String} selector 被委托对象 可是复杂选择器
			 * @param {Function} fn  回调
			 * @description 
			 * 	事件委托的小实现
			 *  delegate实现与jQuery实现，冒泡target对比测试,结果相同
			 *  delegate实现与jQuery实现,判断是否阻止默认事件,结果相同
			 * @example
			 * 	var body = document.querySelector("body");
			 *  delegate(body,'click','.stop a',function(e) {
			 *		e.preventDefault();  阻止默认事件
			 *		console.log(e.target);
			 * 		console.log(e.currentTarget); 
			 * 		！！！！currentTarget 返回结果与jq不同！！！！
			 *       jq返回的为 .stop下的 a 对象
			 * 		 delegate 返回为 body 对象
			 * 		return false; 阻止冒泡
			 *	})
			 */
			function delegate(agent,type,selector,fn) {
                //为了复杂的选择器实现
                agent.addEventListener(type,function(e) {

					var target = e.target;
					var ctarget = e.currentTarget;
                    var bubble = true;
                    console.log(target,'我是target');
                    console.log(ctarget,'我是cTarget');
					while(bubble && target != ctarget) {
						if(filiter(agent,selector,target)) {
							bubble = fn.call(target,e);
                            return bubble;
                        }
						target = target.parentNode;
					}
				},false);
                function filiter(agent,selector,target) {
					var nodes = agent.querySelectorAll(selector);
					for (var i = 0; i < nodes.length; i++) {
						if (nodes[i] == target) {
							return true;
						}
					}
				}
			}
			
			var body = document.querySelector("body");
			var box = document.getElementById("box");
			
            delegate(body, 'click', '.child', function (e) {
                return false;
                //阻止冒泡
            });

		</script>
	</body>
</html>